package com.gpframework.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static org.apache.http.client.utils.DateUtils.formatDate;

/**
 * 时间工具类
 *
 * @Author gpframework
 */
@Slf4j
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYMMDD = "yyMMdd";

    public static String DD = "dd";

    public static String MM_DD = "MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String YYYY_WW = "yyyy-ww";

    public static String YYYY_MM_DD_00_00_00 = "yyyy-MM-dd 00:00:00";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 年月日时分秒(无下划线) yyyyMMddHHmmss
     */
    public static final String dtLong = "yyyyMMddHHmmss";

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 格式：年份-第几周  例如：2021-01
     */
    public static final String getWeekTime() {
        return dateTimeNow(YYYY_WW);
    }

    /**
     * 格式：年-月  例如：2021-01
     */
    public static final String getMonthTime() {
        return dateTimeNow(YYYY_MM);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    /*public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }*/
    public static String getDatePoor(Date endDate, Date nowDate) {

        long ny = 24 * 60 * 60 * 365;//每年秒数
        long nM = 24 * 60 * 60 * 30;//每月秒数
        long nd = 24 * 60 * 60;//每天秒数
        long nh = 60 * 60;//每小时秒数
        long nm = 60;//每分钟秒数
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        long diff = (nowDate.getTime() - endDate.getTime()) / 1000; // 获得两个时间的秒时间差异

        long year = diff / ny;   // 计算差多少年
        if (year == 0) {
            long month = diff / nM;   // 计算差多少月
            if (month == 0) {
                long day = diff / nd;   // 计算差多少天
                if (day == 0) {
                    long hour = diff / nh; // 计算差多少小时
                    if (hour == 0) {
                        long min = diff / nm;  // 计算差多少分钟
                        if (min == 0) {
                            return "刚刚";
                        } else {
                            return min + "分钟前";
                        }
                    } else {
                        return hour + "小时前";
                    }
                } else {
                    return day + "天前";
                }
            } else {
                return month + "个月前";
            }
        } else {
            return simpleDateFormat.format(endDate);
        }

    }

    public static String findDatePoor(Date endDate, Date nowDate) {
        long ny = 24 * 60 * 60 * 365;//每年秒数
        long nM = 24 * 60 * 60 * 30;//每月秒数
        long nd = 24 * 60 * 60;//每天秒数
        long nh = 60 * 60;//每小时秒数
        long nm = 60;//每分钟秒数
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long diff = (nowDate.getTime() - endDate.getTime()) / 1000; // 获得两个时间的秒时间差异

        long year = diff / ny;   // 计算差多少年
        if (year == 0) {
            long month = diff / nM;   // 计算差多少月
            if (month == 0) {
                long day = diff / nd;   // 计算差多少天
                if (day == 0) {
                    long hour = diff / nh; // 计算差多少小时
                    if (hour == 0) {
                        long min = diff / nm;  // 计算差多少分钟
                        if (min == 0) {
                            return "刚刚";
                        } else {
                            return min + "分钟前";
                        }
                    } else {
                        return hour + "小时前";
                    }
                } else {
                    return day + "天";
                }
            } else {
                return month + "个月前";
            }
        } else {
            return simpleDateFormat.format(endDate);
        }

    }

    /**
     * 计算两个时间差(分钟)
     */
    public static long getDateSecondDiff(Date endDate, Date beginDate) {
        long currentTime = endDate.getTime();
        //从对象中拿到时间
        long createTime = beginDate.getTime();
        long diff = (currentTime - createTime) / 1000;
        return diff;
    }

    /**
     * 计算两个时间差(分钟)
     */
    public static long getDateMinDiff(Date endDate, Date beginDate) {
        long currentTime = endDate.getTime();
        //从对象中拿到时间
        long createTime = beginDate.getTime();
        long diff = (currentTime - createTime) / 1000 / 60;
        return diff;
    }

    /**
     * 计算两个时间差(小时)
     */
    public static long getDateHourDiff(Date endDate, Date beginDate) {
        long currentTime = endDate.getTime();
        //从对象中拿到时间
        long createTime = beginDate.getTime();
        long diff = (currentTime - createTime) / 1000 / 60 / 60;
        return diff;
    }

    public static Long getDatePoor(Date oneDate, Date otherDate, String diffName) {

        // 获得两个时间的毫秒时间差异
        long diff = oneDate.getTime() - otherDate.getTime();
        long result = 0;

        switch (diffName) {
            case "day":
                long nd = 1000 * 24 * 60 * 60;
                // 计算差多少天
                result = diff / nd;
                break;
            case "hour":
                long nh = 1000 * 60 * 60;
                // 计算差多少小时
                result = diff / nh;
                break;
            case "min":
                long nm = 1000 * 60;
                // 计算差多少分钟
                result = diff / nm;
                break;
            case "sec":
                long ns = 1000;
                // 计算差多少秒
                result = diff / ns;
                break;
            default:
        }
        return result;
    }

    /**
     * 获取X秒后的时间
     *
     * @param date
     * @param second
     * @return
     */
    public static Date getAfterSecond(Date date, int second) {
        Calendar cal = Calendar.getInstance();
        if (null != date) {
            cal.setTime(date);
        }
        cal.add(Calendar.SECOND, +second);
        Date time = cal.getTime();
        return time;
    }

    /**
     * 获取X分钟后的时间
     *
     * @param date
     * @param minute
     * @return
     */
    public static Date getAfterMinute(Date date, int minute) {
        Calendar cal = Calendar.getInstance();
        if (null != date) {
            cal.setTime(date);
        }
        cal.add(Calendar.MINUTE, +minute);
        Date time = cal.getTime();
        return time;
    }

    /**
     * 获取X小时后的时间
     *
     * @param date
     * @param minute
     * @return
     */
    public static Date getAfterHour(Date date, int minute) {
        Calendar cal = Calendar.getInstance();
        if (null != date) {
            cal.setTime(date);
        }
        cal.add(Calendar.HOUR, +minute);
        Date time = cal.getTime();
        return time;
    }

    /**
     * 获取X天后的时间
     *
     * @param date
     * @param day
     * @return
     */
    public static Date getAfterDay(Date date, int day) {
        Calendar cal = Calendar.getInstance();
        if (null != date) {
            cal.setTime(date);
        }
        cal.add(Calendar.DAY_OF_MONTH, +day);
        Date time = cal.getTime();
        return time;
    }

    /**
     * 获取X天前的时间
     *
     * @param date
     * @param dayNum
     * @return
     */
    public static Date getBeforeDay(Date date, int dayNum) {
        Calendar cal = Calendar.getInstance();
        if (null != date) {
            cal.setTime(date);
        }
        cal.add(Calendar.DATE, -dayNum);
        Date time = cal.getTime();
        return time;
    }


    /**
     * 两个日期中间的月份
     *
     * @param minDate
     * @param maxDate
     * @return
     */
    public static List<String> getMonthBetween(String minDate, String maxDate) throws ParseException {
        ArrayList<String> result = new ArrayList<String>();
        //格式化为年月
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(minDate));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(maxDate));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }

        return result;
    }

    /**
     * 两个日期中间的天数
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> findDates(String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = new ArrayList<>();
        try {
            // 使用SimpleDateFormat将字符串转换为Date
            Date startDate = sdf.parse(startTime);
            // 使用SimpleDateFormat将字符串转换为Date
            Date endDate = sdf.parse(endTime);
            // 获取Calendar的实例
            Calendar startCal = Calendar.getInstance();
            // 将开始的Date设置到Calendar中
            startCal.setTime(startDate);
            // 将开始时间添加到列表中
            dateList.add(startTime);
            // 判断如果endDate在startDate之后则为true
            while (endDate.after(startCal.getTime())) {
                // 在当前时间的基础上加一天
                startCal.add(Calendar.DAY_OF_MONTH, 1);
                // 添加到列表中
                dateList.add(sdf.format(startCal.getTime()));
            }
        } catch (ParseException e) {
            log.error("异常信息", e);
        }
        return dateList;
    }

    /**
     * 计算time2减去time1的差值(秒数) 差值只设置 几天 几个小时 或 几分钟
     * 根据差值返回多长之间前或多长时间后
     */
    public static Long getDistanceTime(long time1, long time2) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        long diff;
        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        day = diff / (24 * 60 * 60 * 1000);
        hour = (diff / (60 * 60 * 1000) - day * 24);
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        if (sec != 0) {
            return sec;
        }
        return 0L;
    }

    /**
     * 得到当前年份字符串 格式（yyyy）
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * 返回系统当前时间(精确到毫秒),作为一个唯一的订单编号
     *
     * @return 以yyyyMMddHHmmss为格式的当前系统时间
     */
    public static String getOrderNum() {
        Date date = new Date();
        DateFormat df = new SimpleDateFormat(dtLong);
        return df.format(date);
    }
    /**
     * 计算视频时长
     * @param source
     * @return
     */
    /*public static String ReadVideoTime(File source) {
        Encoder encoder = new Encoder();
        String length = "";
        try {
            MultimediaInfo m = encoder.getInfo(source);
            long ls = m.getDuration()/1000;
            int hour = (int) (ls/3600);
            int minute = (int) (ls%3600)/60;
            int second = (int) (ls-hour*3600-minute*60);
            if (hour >= 10) {
                length += hour + ":";
            } else if (hour > 0) {
                length += "0" + hour + ":";
            }
            if (minute >= 10) {
                length += minute + ":";
            } else if (minute > 0) {
                length += "0" + minute + ":";
            } else {
                length += "00" + ":";
            }
            if (second >= 10) {
                length += second;
            } else if (second > 0) {
                length += "0" + second;
            } else {
                length += "00";
            }
//			length = hour+":"+minute+":"+second;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return length;
    }*/

    /**
     * 得到当前月份字符串 格式（MM）
     */
    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String getDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }

}
